<template>
  <van-form>
    <van-field
      v-model="firstAmount"
      type="number"
      :label="firstLabel"
      right-icon="more-o"
      @click-right-icon="togglePicker('first')"
      @blur="convert('first')"
    />
    <van-field
      v-model="secondAmount"
      type="number"
      :label="secondLabel"
      right-icon="more-o"
      @click-right-icon="togglePicker('second')"
      @blur="convert('second')"
    />
    <div style="margin: 16px">
      <van-button :loading="isLoading" loading-type="spinner" round block type="primary">
        转换
      </van-button>
    </div>
  </van-form>

  <!-- 选择器 -->
  <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
    <van-picker
      :columns="columns"
      @cancel="showPicker = false"
      @confirm="onConfirm"
    />
  </van-popup>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getCurrencyList } from "@/services/apiGetCurrency";
import { useTogglePicker } from "@/features/Currency/useTogglePicker";
import { useCurrencyConvert } from "@/features/Currency/useCurrencyConvert";

const columns = ref([]);
const currentFlag = ref("first");

onMounted(async () => {
  const currencyList = await getCurrencyList();
  columns.value = Object.keys(currencyList).map((key) => ({
    text: key.toUpperCase(),
    value: key,
  }));
});

const { showPicker, isFirst, togglePicker } = useTogglePicker(currentFlag);

const {
  firstLabel,
  firstAmount,
  secondLabel,
  secondAmount,
  isLoading,

  convert,
  onConfirm,
} = useCurrencyConvert(isFirst, showPicker);
</script>
